const HttpException = require("../exceptions/http_expetion");
const Article = require("../models/article");
const Tag = require("../models/tag");
const User = require("../models/user");

function handleArticle(article,author,count){
  const nweTags = []
  for (const i of article.dataValues.tags) {
    nweTags.push(i.name)
  }
  article.dataValues.tags = nweTags
  delete author.dataValues.password
  delete author.dataValues.email
  article.dataValues.author = author

  article.dataValues.favoriteCount = count
  article.dataValues.favorited = true

  return article.dataValues
}

//添加喜欢
module.exports.addFavorite = async (req, res, next) => {
  try {
   //获取参数：文章
   const {slug} = req.params
   //获取文章
   let article =await Article.findByPk(slug,{include:Tag})
   if(!article){
     throw new HttpException(404,'获取喜欢文章不存在！！！','article is not found!!!')
   }
   //文章添加喜欢用户
   await article.addUsers(req.user.email)
   //获取文章作者
   const author = await article.getUser()
   //获取喜欢个数
   const count = await article.countUsers()
   //数据处理
   article = handleArticle(article,author,count)
   //响应数据
   res.status(200)
   .json({
     status:1,
     message:'添加喜欢文章成功',
     data:article
   })


  } catch (err) {
    next(err);
  }
};

//取消喜欢
module.exports.removeFavorite = async (req, res, next) => {
  try {
   //获取参数：文章
   const {slug} = req.params
   //获取文章
   let article =await Article.findByPk(slug,{include:Tag})
   if(!article){
     throw new HttpException(404,'获取喜欢文章不存在！！！','article is not found!!!')
   }
   //文章取消喜欢用户
   await article.removeUsers(req.user.email)
   //获取文章作者
   const author = await article.getUser()
   //获取喜欢个数
   const count = await article.countUsers()
   //数据处理
   article = handleArticle(article,author,count)
   //响应数据
   res.status(200)
   .json({
     status:1,
     message:'取消喜欢文章成功',
     data:article
   })

  } catch (err) {
    next(err);
  }
};

